package com.zlyx.easy.access;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;

import com.zlyx.easy.access.abstracts.AbstractAccesser;
import com.zlyx.easy.access.annotations.EasyAccesser;
import com.zlyx.easy.core.factory.defaults.annotations.FactoryBean;
import com.zlyx.easy.core.factory.interfaces.FactoryBeanDefiner;
import com.zlyx.easy.core.loggers.Logger;
import com.zlyx.easy.core.utils.StringUtils;

/**
 * @Auth 赵光
 * @Describle
 * @2018年12月31日 下午5:52:03
 */
@FactoryBean(annotationClass = EasyAccesser.class, todo = "accesserFactoryBean")
public class AccesserFactoryBean implements FactoryBeanDefiner {

	@Override
	public Object excute(Class<?> proxyClass, Method method, Object[] args) {
		try {
			Class<?> tClass = null;
			if (proxyClass.getGenericInterfaces() != null && proxyClass.getGenericInterfaces().length > 0) {
				tClass = (Class<?>) ((ParameterizedType) proxyClass.getGenericInterfaces()[0])
						.getActualTypeArguments()[0];
			}
			if (AbstractAccesser.class == method.getDeclaringClass()) {
				return AccesserManager.getAccesser("").doAccess(tClass, method, args);
			} else {
				EasyAccesser accesserAnno = method.getDeclaringClass().getAnnotation(EasyAccesser.class);
				if ("".equals(accesserAnno.value()) && AccesserManager.size() > 1) {
					Logger.err(method.getDeclaringClass(), "请@Accesser注解的name值指定具体的分支!");
					return null;
				}
				String key = StringUtils.emptyOfNull(accesserAnno.value());
				return AccesserManager.getAccesser(key).doAccess(tClass, method, args);
			}
		} catch (Exception e) {
			Logger.err(method.getDeclaringClass(), e);
		}
		return null;
	}
}
